package com.gph.saviorframework.shiro.filter;

import com.gph.saviorframework.security.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * Created by savior on 2016/8/29.
 */
public class MyFormAuthenticationFilter extends FormAuthenticationFilter {

    @Autowired
    private UserService userService;

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if(request.getAttribute(getFailureKeyAttribute())!=null){
            return true;
        }
        return super.onAccessDenied(request, response);
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        AuthenticationToken token = createToken(request, response);
        if (token == null) {
            String msg = "createToken method implementation returned null. A valid non-null AuthenticationToken " +
                    "must be created in order to execute a login attempt.";
            throw new IllegalStateException(msg);
        }
        try {
            Subject subject = getSubject(request, response);
            subject.login(token);
            Session session = subject.getSession();
            session.setAttribute("_CURRENT_USER_", userService.get(getUsername(request)));
            session.setAttribute("_USERNAME_", getUsername(request));
            return onLoginSuccess(token, subject, request, response);
        }
        catch (AuthenticationException e) {
            e.printStackTrace();
            return onLoginFailure(token, e, request, response);
        }
    }
}
